package com.siblings.loan.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.lib.base.utils.DensityUtils
import com.siblings.lib_baseadapter.SIBOnItemChildClickListener
import com.siblings.lib_baseadapter.SIBRecyclerViewAdapter
import com.siblings.lib_baseadapter.SIBViewHolderHelper
import com.siblings.loan.R
import com.siblings.loan.app.Apps
import com.siblings.loan.databinding.DialogBirthdayBinding
import com.siblings.loan.databinding.ItemMonthBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.utils.decoration.GridSpacingItemDecoration
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.utils.helper.DateHelper
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 * Siblings
 * @Author wwdeng
 * @CreateTime: 2024/7/10 13:54
 * @Annotation：流程选择出生日期
 */
class BirthdayDialog: ProDialog {
    private lateinit var binding: DialogBirthdayBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    /* 日期 */
    private var mDayAdapter: DayAdapter? = null

    //年
    private var showYear = DateHelper.getCurtYear()
    //月
    private var isInit = true
    private var showMonth = DateHelper.getCurtMonth()
    //日
    private var showDay = DateHelper.getCurtDay()

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context?, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun initWindow() {
        val params = window!!.attributes
        params.width = Apps.app.getPhoneWidth()
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window!!.setGravity(Gravity.BOTTOM)
    }

    override fun getRootView(): View {
        binding = DialogBirthdayBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initMonthTabLayout()
        initRvDay()
    }

    override fun initListener() {
        setOnClickListener(R.id.btnDone)
        //上一年
        binding.imgLastYear.setOnClickListener {
            showYear--
            showYear()
            showDay()
        }
        //下一年
        binding.imgNextYear.setOnClickListener {
            showYear++
            showYear()
            showDay()
        }
    }

    override fun initData() {
        showYear()
        showMonth()
        showDay()
    }

    @SuppressLint("SimpleDateFormat")
    override fun onViewClick(v: View?) {
        when (v!!.id) {
            R.id.btnDone -> {//提交
                val selectDay = getSelectDay()
                if (selectDay == 0){
                    showToast(context.getString(R.string.tips_select_birth_error))
                    return
                }
                dismiss()
                var formatDay = "$selectDay"
                if (selectDay < 10){
                    formatDay = "0$selectDay"
                }

                val calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, showYear)
                calendar.set(Calendar.MONTH, showMonth-1)
                calendar.set(Calendar.DAY_OF_MONTH, selectDay)
                val obj = JSONObject()
                obj.put("showDate","$showYear-${DateHelper.getMonthList()[showMonth - 1].optString("month")}-$formatDay")
                obj.put("subDate",SimpleDateFormat("yyyy-MM-dd").format(calendar.timeInMillis))
                if (mCallback != null){
                    mCallback!!.completed(obj)
                }
            }
        }
    }

    interface IDialogCallback {
        fun completed(selectDate: JSONObject)
    }

    /**
     * 设置月份
     */
    private fun initMonthTabLayout(){
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab!!.setSelected(tab)
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab!!.setUnselected()
            }
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initRvDay() {
        binding.rvDay.setHasFixedSize(true)
        binding.rvDay.isNestedScrollingEnabled = false
        binding.rvDay.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(12f)
        binding.rvDay.addItemDecoration(GridSpacingItemDecoration(7,decoration,true))
        val layoutManager = GridLayoutManager(context,7)
        binding.rvDay.layoutManager = layoutManager
        mDayAdapter = DayAdapter(binding.rvDay)
        binding.rvDay.adapter = mDayAdapter
        binding.rvDay.itemAnimator = DefaultItemAnimator()
        mDayAdapter!!.setOnItemChildClickListener(SIBOnItemChildClickListener { _, _, position ->
            val item = mDayAdapter!!.getItem(position)
            if (item.optBoolean("isSelect") || item.optInt("day") == 0){
                return@SIBOnItemChildClickListener
            }
            for (i in 0..<mDayAdapter!!.itemCount){
                val obj = mDayAdapter!!.getItem(i)
                obj.put("isSelect",false)
                if (i == position){
                    obj.put("isSelect",true)
                }
            }
            mDayAdapter!!.notifyDataSetChanged()
        })
    }

    /**
     * 选中状态
     */
    fun TabLayout.Tab.setSelected(tab: TabLayout.Tab) {
        this.customView?.let {
            val textMonth = it.findViewById<TextView>(R.id.textMonth)
            textMonth.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
            textMonth.setTextColor(Color.parseColor("#FFFFFFFF"))
            textMonth.setBackgroundResource(R.drawable.sib_radius_fill_theme_4)
        }
        if (!isInit){
            showMonth = tab.position + 1
            showDay()
        }
        isInit = false
    }

    /**
     * 未选中状态
     */
    fun TabLayout.Tab.setUnselected() {
        this.customView?.let {
            val textMonth = it.findViewById<TextView>(R.id.textMonth)
            textMonth.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
            textMonth.setTextColor(Color.parseColor("#FF666666"))
            textMonth.setBackgroundColor(Color.parseColor("#00000000"))
        }
    }

    /**
     * 设置年份
     */
    private fun showYear(){
        binding.textYear.text = "$showYear"
    }

    /**
     * 设置月份
     */
    private fun showMonth(){
        binding.tabLayout.removeAllTabs()
        val monthList = DateHelper.getMonthList()
        monthList.forEach {
            it.put("year",showYear)
            val tab = binding.tabLayout.newTab()
            val tabBinding = ItemMonthBinding.inflate(LayoutInflater.from(context))
            tabBinding.textMonth.text = it.optString("month")
            tab.setCustomView(tabBinding.root)
            binding.tabLayout.addTab(tab)
        }

        val curtIndex = showMonth - 1
        binding.tabLayout.getTabAt(curtIndex)!!.select()
        binding.tabLayout.post {
            binding.tabLayout.setScrollPosition(curtIndex,0f,false)
        }
    }

    /**
     * 设置日期
     */
    private fun showDay(){
        val dayList = arrayListOf<JSONObject>()
        //指定年月的1号是星期几
        val week = DateHelper.getDayOfWeek(showYear,showMonth,1)
        for (i in 0..<week){
            val item  = JSONObject()
            item.put("year",0)
            item.put("month",0)
            item.put("day",0)
            dayList.add(item)
        }
        dayList.addAll(DateHelper.getDayList(showYear,showMonth))
        for (i in 0..<dayList.size){
            val day = dayList[i]
            day.put("isSelect",false)
            if (showYear == DateHelper.getCurtYear() && showMonth == DateHelper.getCurtMonth() && day.optInt("day") == showDay){
                day.put("isSelect",true)
            }
        }
        mDayAdapter!!.data = dayList
    }

    /**
     * 获取选中的日期
     */
    private fun getSelectDay(): Int{
        var day = 0
        for (i in 0..<mDayAdapter!!.itemCount){
            val item = mDayAdapter!!.getItem(i)
            if (item.optBoolean("isSelect")){
                day = item.optInt("day")
                break
            }
        }
        return day
    }

    /**
     * 日期
     */
    internal inner class DayAdapter(recyclerView: RecyclerView?) :
        SIBRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.item_day) {
        override fun setItemChildListener(helper: SIBViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.textDay) //点击Item
        }

        override fun fillData(helper: SIBViewHolderHelper, position: Int, model: JSONObject) {
            val textDay = helper.getTextView(R.id.textDay)
            val showDay = model.optInt("day")
            if (showDay == 0){
                textDay.text = ""
            } else {
                textDay.text = "$showDay"
            }

            if (model.optBoolean("isSelect")){
                textDay.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                textDay.setTextColor(Color.parseColor("#FFFFFFFF"))
                textDay.setBackgroundResource(R.drawable.sib_radius_fill_theme_4)
            } else {
                textDay.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
                textDay.setTextColor(Color.parseColor("#FF000000"))
                textDay.setBackgroundColor(Color.parseColor("#00000000"))
            }
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.DIALOG.SIB_DIALOG_BIRTHDAY_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addSibEventAction(SibEventType.DIALOG.SIB_DIALOG_BIRTHDAY_DISMISS,eventRemark)
    }
}